package cluster

import (
	"context"
	"kms-backend/config"
	"kms-backend/utils/logs"
	"net/http"

	"github.com/gin-gonic/gin"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func List(r *gin.Context) {
	logs.Debug(nil, "展示集群")
	// namespace中有很多其他的Secret
	// ListOptions可以根据LabelSelector 筛选出我们需要的Secret
	returnData := config.ReturnData{}
	listOptions := metav1.ListOptions{
		LabelSelector: config.ClusterConfingSecretKey + "=" + config.ClusterConfingSecretValue,
	}
	secretList, err := config.InClusterClientSet.CoreV1().Secrets(config.MetadataNamespace).List(context.TODO(), listOptions)
	if err != nil {
		// 查询失败
		logs.Error(nil, "查询集群列表失败: "+err.Error())
		msg := "查询失败: " + err.Error()
		returnData.Message = msg
		returnData.Status = 400
		r.JSON(http.StatusOK, returnData)
		return
	} else {
		logs.Info(nil, "查询集群列表成功")
		returnData.Status = 200
		returnData.Message = "查询集群列表成功"
		// 将secretList存入retrunData.Data 返回给前端
		// Secret 里面的信息也只需要Annotations的内容
		clusterList := []map[string]string{}
		for _, v := range secretList.Items {
			anno := v.Annotations
			clusterList = append(clusterList, anno)
		}
		returnData.Data = make(map[string]interface{})
		returnData.Data["items"] = clusterList
		r.JSON(200, returnData)
	}

}
